<?php if ( ! defined('ABSPATH')) exit('restricted access'); /** stop direct script access */

/**
 * Handle all ajax/jquery requests here for theme fronend
 * @package WordPress
 * @subpackage WelCare
 * @author	WP Nukes Developers Team (Allan)
 * @link	http://www.wpnukes.com
 * @since	Version 1.0
 */
 
 
/**
 * Class that handles all ajax calls and their responses
 * @package WordPress
 * @subpackage WelCare
 * @author	WP Nukes Developers Team (Allan)
 * @link	http://www.wpnukes.com
 * @since	Version 1.0
 */
 
class FW_Ajax_Handler
{
	private $_webnukes = array(), $data = array();
	
	function __construct()
	{
		$this->_webnukes = &$GLOBALS['_webnukes'];
		
		/** handle all ajax requests that comes through myspecialaction ajax action */
		add_action('wp_ajax_nopriv_fw_ajax_callback', array($this, 'Ajax_Handler'));
		add_action('wp_ajax_fw_ajax_callback', array($this, 'Ajax_Handler'));
	}
	
	function Ajax_Handler()
	{
		$this->data = &$_REQUEST;
		
		$subaction = $this->_webnukes->kvalue($this->data, 'subaction');
	
		if(method_exists($this, $subaction)) $this->$subaction();
		else exit( __('Unknown ajax request sent.', THEME_NAME));
		exit;
	}
	
	private function data($data)
	{
		if($data) exit($data);
		else exit(__('No Data', THEME_NAME));
		exit;
	}
	
	/**
	 * add/update doctors ratings to user meta table
	 *
	 * @param	string	$type		type of the response message either error or success
	 * @param	string	$msg		translated message to send as a response.
	 * @return 	string	Return the respose according to the request
	 */
	private function msg($type = 'success', $msg = '')
	{
		/** Success message after sending email */
		$alert = ($type == 'success') ? __('SUCCESS', THEME_NAME) : __('ERROR', THEME_NAME);
		return '<p class="'.$type.'"> 
					<img alt="" src="'.get_template_directory_uri().'/images/'.$type.'.png"> 
					<strong>'.$alert.'</strong> - '.$msg.'
				</p>';
	}
	 
	/**
	 * add/update doctors ratings to user meta table
	 *
	 * @return string	Return the respose according to the request
	 */
	private function child_pages()
	{
		$output = '';
		/** If any data is posted then continue */
		if(count($this->data)){
			
			/** if the request for getting the child pages of a requested page */
			if($page_id = $this->_webnukes->kvalue($this->data, 'page_id')){
				
				$output .= '<option value="0">'.__('Select Value', THEME_NAME).'</option>';
				$pages = get_pages(array('child_of'=>$page_id));
				
				if($pages){
					foreach($pages as $page){
						$output .= '<option value="'.get_permalink($page->ID).'">'.$page->post_title.'</option>';
					}
				}
			}
		}
		
		$this->data($output);
	}
	
	/**
	 * add/update doctors ratings to user meta table
	 *
	 * @return string	Return the respose according to the request
	 */
	private function doctors_rating()
	{
		
		/** if the request is for doctor rating */
		if($type = $this->_webnukes->kvalue($this->data, 'type'))
		{
			
			$id = $this->_webnukes->kvalue($this->data, 'doctor_id');
			$value = $this->_webnukes->kvalue($this->data, 'value');

			$ip = $_SERVER['REMOTE_ADDR'];

			$user_meta = get_user_meta($id, $type, true);
			$rating = get_user_meta($id, 'rating', true);
		
			$meta_ips = $this->_webnukes->kvalue($user_meta, 'ips');
			
			if($user_meta && $meta_ips)
			{
				if(in_array($ip, $user_meta['ips'])) return;
			}
				
			$user_meta['ips'] = (!in_array($ip, (array)$meta_ips)) ? array_merge((array)$meta_ips, array($ip)) : $meta_ips;
			$user_meta['rating'][] = ($this->_webnukes->kvalue($user_meta, 'rating')) ? $value : $value;
			$user_meta['number'] = ($this->_webnukes->kvalue($user_meta, 'number')) ? ((int)$this->_webnukes->kvalue($user_meta, 'number') + 1) : 1;
			$user_meta['avg'] = (array_sum((array)$this->_webnukes->kvalue($user_meta, 'rating')) / $this->_webnukes->kvalue($user_meta, 'number'));
		
			update_user_meta($id, $type, $user_meta); /** Update the new value */
			
			if($type == 'doctor_heart') update_user_meta($id, 'rating', round($user_meta['avg']));
		}
	}
	
	/**
	 * Validate and email a data to the admin when a contact form submission is executed.
	 *
	 * @param	array		$data		data that is posted via contact form.
	 * @return	array/sting 			Return the response either successfull or failure.
	 *
	 * @TODO		Submit Contact from that is generated via form builder.
	 */
	 
	public function save_contact($data = '')
	{
		$obj = isset($this) ? $this : new FW_Ajax_Handler;
		$data = (!$data) ? $obj->data : $data;
		global $_webnukes;
		/** Load validation class */
		$this->_webnukes->load('validation_class');
		
		/** Add validation rules for all the fields in the contact form */
		$this->_webnukes->validation->set_rules('contact_email', 'Email', 'required|valid_email');
		$this->_webnukes->validation->set_rules('contact_name', 'Name', 'required|min_length[5]');
		$this->_webnukes->validation->set_rules('contact_website', 'Website', 'required|valid_url');
		$this->_webnukes->validation->set_rules('contact_message', 'Message', 'required|trim');
		$contact_information = $_webnukes->get_settings('contact_information'); /** get contact details from options */
		if($contact_information['captcha'] == 'active' && $contact_information['key'])
		{
			require_once('recaptchalib.php');
								
			$resp = recaptcha_check_answer ($settings['api'],
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);
								print_r($resp);exit;

			  if ( ! $resp->is_valid)
			  {
				  $message = $obj->msg('capthca', __('Invalid captcha entered, please try again', THEME_NAME));
			  }
		}

		
		/** If validation is true then shoute an email and store a success response in a variable */
		if($this->_webnukes->validation->run() !== FALSE && empty($this->_webnukes->validation->_error_array))
		{	
			$name = $data['contact_name'];
			$email = $data['contact_email'];
			
			$new_data = array();
			
			/** Create an email body */
			foreach($data as $k=>$v)
			{
				$new_data[] = ucwords(str_replace('_', ' ', $k)).":\t\t".$v."\r\n\r\n";
			}
			
			$subject = __('Contact Us', THEME_NAME);
			$headers = 'From: '.$name.' <'.$email.'>' . "\r\n";
	
			wp_mail(get_option('admin_email'), $subject, implode("\r\n",$new_data), $headers);
	
			/** Success message after sending email */
			$message = $obj->msg('success', __('Your message is submitted succesfully', THEME_NAME));
								
			/** Store a message into a $_POST variable to be printed on frontend */
			$_POST['submission_message'] = $message; 
	
		}else{
			
			/** Get the array of errors */
			$errors = (!is_array($this->_webnukes->validation->_error_array)) ? array($this->_webnukes->validation->_error_array) : $this->_webnukes->validation->_error_array ;
	
			/** Prepare errors HTML to show on frontend */
			$messages = '';
			foreach($errors as $k=>$message)
			{
				$messages .= $obj->msg('error', $message);
			}
			
			/** Store the error messages into $_POST variable */
			$_POST['submission_message'] = $messages;
		}
		
		/** If form is submitted through ajax then print the message and stop the execution */
		if($this->_webnukes->kvalue($data, 'ajax')) $obj->data($_POST['submission_message']);
	}
	
	/**
	 * Validate and email a data to the admin when a contact form submission is executed.
	 *
	 * @param	array		$data		data that is posted via symptom checker form.
	 * @return	array/sting 			Return the response either successfull or failure.
	 */
	private function symptoms_checker()
	{
		/** Include the checker.php on ajax requests */
		include_once(get_template_directory().'/symptoms_checker/ajax.php');
	}
}

new FW_Ajax_Handler;